<template>
  <div class="app-container">
    <el-form :inline="true" :model="recordInfo.queryForm" class="demo-form-inline">
      <el-form-item label="会员手机号/ID">
        <el-input v-model="recordInfo.queryForm.memberKeyword" placeholder="会员手机号/ID" clearable style="width: 220px;" />
      </el-form-item>

      <el-form-item label="易购卡">
        <el-select v-model="recordInfo.queryForm.cardType" clearable placeholder="易购卡" style="width: 220px">
          <el-option v-for="item in cardTypeList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="会员来源">
        <el-select v-model="recordInfo.queryForm.memberSource" clearable placeholder="会员来源" style="width: 220px">
          <el-option v-for="item in memberSourceList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="会员状态">
        <el-select v-model="recordInfo.queryForm.memberStatus" clearable placeholder="会员状态" style="width: 220px">
          <el-option v-for="item in memberStatusList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="注册时间">
        <el-date-picker
          v-model="registerTimeValue"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="defaultTime"
          @change="dateChange('registerTimeValue')"
          style="width: 300px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="openDetail(1)">打开弹窗</el-button>
        <el-button @click="editMember1(1)">打开编辑</el-button>
      </el-form-item>
    </el-form>

    <div style="display: flex;justify-content: space-between;align-items: center; margin-bottom: 10px;">
      <h5 style="margin: 0; font-size: 16px;">会员列表</h5>
    </div>

    <el-table
      v-loading="recordInfo.loading"
      class="table-default"
      :data="recordInfo.list"
      border
      style="width: 100%"
      max-height="600"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column label="会员信息" width="260" align="center">
        <template slot-scope="scope">
          <div class="member-info-cell">
            <img :src="scope.row.memberAvatar" class="avatar-sm">
            <div class="member-text">
              <p class="name">{{ scope.row.memberName }}</p>
              <p class="id-phone">ID: {{ scope.row.memberId }}</p>
              <p class="id-phone">{{ scope.row.memberPhone }}</p>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="availablePoints" label="可用积分" align="center" />
      <el-table-column prop="availableBalance" label="可用余额" align="center" />
      <el-table-column prop="cardCount" label="易购卡数量" align="center" />
      <el-table-column prop="cardBalance" label="易购卡余额" align="center" />
      <el-table-column prop="registerTime" label="注册时间" align="center" />
      <el-table-column prop="lastLoginTime" label="最近一次登录" align="center" />
      <el-table-column prop="daysSinceLogin" label="多久未登录" align="center" />

      <el-table-column label="操作" fixed="right" width="140" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="goDetail(scope.row)">详情</el-button>
          <el-button type="text" size="small" @click="editMember(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="recordInfo.total > 0"
      :total="recordInfo.total"
      :page.sync="recordInfo.queryForm.page"
      :limit.sync="recordInfo.queryForm.pageSize"
      @pagination="getRecordList"
      :page-sizes="[10, 20, 50, 100]"
    />
    <member-detail-dialog
      :visible.sync="showDetailDialog"
      :member-id="currentMemberId"
    />
    <member-edit-dialog
      :visible.sync="showEditDialog"
      :member-id="currentMemberId"
      @success="handleSaveSuccess"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import filters from '@/filters/index'
import ListMixin from '@/mixins/modules/list'
import messageMixin from '@/mixins/modules/message'
import Pagination from '@/components/Pagination'
import MemberDetailDialog from './components/MemberDetailDialog.vue'
import MemberEditDialog from './components/MemberEditDialog.vue'

export default {
  components: {
    Pagination,
    MemberDetailDialog,
    MemberEditDialog
  },
  filters: { ...filters },
  mixins: [ListMixin, messageMixin],
  data() {
    return {
      // 绑定到日期选择器的值
      registerTimeValue: null,
      showEditDialog: false,
      showDetailDialog: false,
      currentMemberId: null,

      recordInfo: {
        queryForm: {
          page: 1,
          pageSize: 10,
          orderBy: 'registerTimeDesc',
          // 查询表单字段
          memberKeyword: '',
          cardType: '',
          memberSource: '',
          memberStatus: '',
          // 注册时间范围参数由 Mixin 自动处理
        },
        requestUrl: this.$api.getMemberList, // 假设存在会员列表接口
        list: [],
        total: 0,
        loading: false
      },

      // 静态数据列表（实际项目可能从 Vuex 或 API 获取）
      cardTypeList: [{ name: '普通卡', value: 1 }, { name: 'VIP卡', value: 2 }, { name: '至尊卡', value: 3 }],
      memberSourceList: [{ name: '线上注册', value: 1 }, { name: '门店导购', value: 2 }, { name: '活动引流', value: 3 }],
      memberStatusList: [{ name: '正常', value: 1 }, { name: '冻结', value: 2 }, { name: '注销', value: 3 }],

      // **关键配置**：告知 Mixin 哪些字段需要进行日期转换
      changeDateNameInfo: {
        registerTimeValue: ['registerTimeStart', 'registerTimeEnd']
      },

      // 覆盖 Mixin 的 getListCallback，用于处理列表数据的格式化
      getListCallback: (res) => {
        if (res.list && res.list.length > 0) {
          res.list.forEach(item => {
            // 1. 格式化时间
            item.registerTime = this.$commonUtils.getShowTime(item.registerTime) // 假设存在
            item.lastLoginTime = this.$commonUtils.getShowTime(item.lastLoginTime) // 假设存在

            // 2. 格式化金额和数量
            item.availableBalance = '￥' + parseFloat(item.availableBalance).toFixed(2)
            item.cardBalance = '￥' + parseFloat(item.cardBalance).toFixed(2)
            item.cardCount = item.cardCount + '张'
            item.daysSinceLogin = item.daysSinceLogin + '天' // 假设后端返回数字

            // 3. 模拟会员信息
            if (!item.memberAvatar) {
              item.memberAvatar = '/static/default-avatar.png' // 默认头像
            }
          })
        }
        // 更新列表和总数
        this.recordInfo.list = res.list || []
        // Mixin 默认会处理总数 this.recordInfo.total = Number(res.count)
      },

      // 覆盖 Mixin 的 beforeRequest，将 DatePicker 值映射到 queryForm
      beforeRequest: () => {
        // 调用 Mixin 的 changeDate 逻辑，将 registerTimeValue 映射到对应的 Start/End 字段
        this.changeDate(this.registerTimeValue, 'registerTimeValue')

        // 确保 returnCount 逻辑正确
        this.recordInfo.queryForm.returnCount = this.recordInfo.queryForm.page === 1

        // 不返回 false，表示继续请求
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },

  methods: {
    openDetail(member) {
      this.currentMemberId = member.memberId
      this.showDetailDialog = true
    },
     editMember1(item) {
      // 设置要编辑的会员ID
      this.currentMemberId = item.memberId
      this.showEditDialog = true
    },
    handleSaveSuccess() {
      this.$message.success('会员信息已更新，正在刷新列表...')
      // 重新加载当前页数据
      this.getRecordList()
    },
    // 查询按钮，利用 Mixin 的 getRecordList
    search() {
      this.recordInfo.queryForm.page = 1
      this.getRecordList()
    },

    // 重置表单，清空所有查询条件
    resetForm() {
      // 业务字段清空
      this.recordInfo.queryForm = {
        page: 1,
        pageSize: 10,
        orderBy: 'registerTimeDesc',
        memberKeyword: '',
        cardType: '',
        memberSource: '',
        memberStatus: '',
      }
      // 日期清空
      this.registerTimeValue = null
      // 重新查询
      this.search()
    },

    // 查看会员详情 (跳转新 Tab)
    goDetail(item) {
      this.$addTab('memberDetailForm', {
        memberId: item.memberId
      }, '会员详情 - ' + item.memberName)
    },

    // 编辑会员信息 (跳转新 Tab)
    editMember(item) {
      this.$addTab('memberEditForm', {
        memberId: item.memberId
      }, '编辑会员 - ' + item.memberName)
    },

    // 新增会员
    addMember() {
      this.$addTab('memberEditForm', {}, '新增会员')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
.demo-form-inline {
  padding-bottom: 5px;
  .el-form-item {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

// 表格内会员信息单元格样式（沿用自订单列表）
.member-info-cell {
  display: flex;
  align-items: center;
  .avatar-sm {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 8px;
    object-fit: cover;
    border: 1px solid #eee;
  }
  .member-text {
    text-align: left;
    p {
      margin: 0;
      line-height: 1.2;
    }
    .name {
      font-weight: bold;
      color: #333;
    }
    .id-phone {
      font-size: 12px;
      color: #999;
    }
  }
}

// 使金额列右对齐
::v-deep .el-table {
    // 可用积分 (第3列), 可用余额 (第4列), 易购卡余额 (第6列)
    .el-table__cell:nth-child(3),
    .el-table__cell:nth-child(4),
    .el-table__cell:nth-child(6) {
        .cell {
            text-align: right;
        }
    }
}
</style>
